<?php
namespace app\api\controller;
use think\Controller;
use think\Validate;
use jwt\Jwt;
use think\Request;

class Common extends Controller{
    protected $return;
    protected $user;
    public function initialize(){
        $this->return = array(
            'status' => 500,
            'message' => '服务器内部错误',
            'code' => 'SERVER_ERROR',
            'data' => ''
        );
        $token = input('token'); 
        if($token){
            $jwt = new Jwt;
            $payload = $jwt->verifyToken($token);
            trace(json_encode($payload), 'payload');
            if (isset($payload['user_id'])) {
                $user = get_user_info($payload['user_id'], 0);
                $this->user = $user;
            }
            $this->sign();
        }
    }

    /**
     * 表单验证
     *
     * @return void
     */
    public function checkParam($rule)
    {
        $post = input();
        $validate = new Validate($rule);
        if (!$validate->check($post)) {
            return $this->showError($validate->getError(), '401');
        }
    }

    // TODO 签名验证
    public function sign(){
        // sign = dev 测试签名，无需验证
        //键值对 app--CLGWWXLRBEJFIS
        //sign = md5(md5(接口名称+签名密钥)+签名密钥)
        $data = $this->request->request();
        $sign = $data['sign'];
        $access_key = $data['accessKey'];
        if($sign && $access_key){
            if($sign != 'dev'){
                $controller = strtolower(str_replace('.','/',$this->request->controller()));
                $action = $controller .'/'. $this->request->action();
                $key = [
                    'app' => 'Avik@123'
                ];
                $server_sign = md5(md5($action . $key[$access_key]) . $key[$access_key]);
                if($server_sign != $sign){
                    $this->return['message'] = '签名错误';
                    $this->return['code'] = 'SIGN_ERROR';
                    $this->return['status'] = 200;
                    return $this->show($this->return);
                }
            }
        }else{
            $this->return['message'] = '签名错误';
            $this->return['code'] = 'SIGN_ERROR';
            $this->return['status'] = 200;
            return $this->show($this->return);
        }
    }

    /**
     * 接口通信统一规范输出
     * @return integer $status 状态码
     * @return string $message 提示信息
     * @return string $code 错误码
     * @return array $data 输出数据
     */
    public function show($obtain){
        $status = $obtain['status'];
        $message = $obtain['message'];
        $code = $obtain['code'];
        $data = $obtain['data'] ? $obtain['data'] : [];
        $expend = $obtain['expend'] ? $obtain['expend'] : [];
        $result = array(
            'status' => $status,
            'message' => urlencode($message),
            'code' => $code,
            'data' => $data,
            'expend' => $expend
        );
        header('Content-Type:application/json; charset=utf-8');
        header('Access-Control-Allow-Origin:*');
        header("Access-Control-Allow-Headers: Content-Type");
        header("Access-Control-Allow-Methods: GET,POST,PUT,DELETE,OPTIONS");
        echo urldecode(json_encode($result,JSON_UNESCAPED_UNICODE));
        exit;
    }

    public function showSuccess($msg, $data=[], $expent=[])
    {
        $res = ['status'=>200,'code'=>'SUCCESS','message'=>$msg,'data'=>$data,'expend'=>$expent];
        $this->show($res);
    }

    public function showError($msg, $code='FAIL')
    {
        $res = ['status'=>200,'code'=>$code,'message'=>$msg];
        $this->show($res);
    }

    public function arrayToJson($data){
        return urldecode(json_encode($data,JSON_UNESCAPED_UNICODE));
    }

    public function checkUserLogin(){
        $token = input('token');
        if (empty($token)) {
            return $this->showError('请提交Token参数', 'NO_LOGIN_ERROR');
        }

        if (empty($this->user)) {
            return $this->showError('用户不存在', 'NO_LOGIN_ERROR');
        }
        if ($this->user['lock'] == 1) {
            return $this->showError('用户已禁用', 'DISABLE_USER');
        }
    }

    /**
     * 获取省市县列表
     */
    public function getCityList($pid){
        if($pid){
            $where = ['parentId'=>$pid];
        }else{
            $where = ['level'=>1];
        }
        $res = db('china')->where($where)->select();
        if($res){
            return $res;
        }else{
            return false;
        }
    }

    public function getCityAllList(){
        $res = db('china')->select();
        if($res){
            return $res;
        }else{
            return false;
        }
    }

    public function getAgeGroupList(){
        $res = db('lj_age_group')->select();
        if($res){
            return $res;
        }else{
            return false;
        }
    }

    public function getReligionGroupList(){
        $res = db('lj_religion')->select();
        if($res){
            return $res;
        }else{
            return false;
        }
    }

    public function getHeightGroupList(){
        $res = db('lj_height_group')->select();
        if($res){
            return $res;
        }else{
            return false;
        }
    }

    public function getChildrenGroupList(){
        $res = db('lj_children_group')->select();
        if($res){
            return $res;
        }else{
            return false;
        }
    }

    /**
     * 时间格式化
     */
    public function format_date($time){
        if(!is_numeric($time)){
            $time=strtotime($time);
        }
        $t=time()-$time;
        $f=array(
            '31536000'=>'年',
            '2592000'=>'个月',
            '604800'=>'星期',
            '86400'=>'天',
            '3600'=>'小时',
            '60'=>'分钟',
            '1'=>'秒'
        );
        foreach ($f as $k=>$v)    {
            if (0 !=$c=floor($t/(int)$k)) {
                return $c.$v.'前';
            }
        }
    }

    public function checkAgent($brand_id)
    {
        $user_id = $this->user['id'];
        $user_type = $this->user['user_type'];
        if($user_type != 3){
            return false;
        }
        $exist = db('goods_brand_agent')->where(['brand_id' => $brand_id, 'user_id' => $user_id, 'status' => 1])->select();
        if(!$exist){
            return false;
        }
        return true;
    }
}